<template>
  <div class="atomic-task-detail-container">
    <div class="page-header">
      <div class="page-title">
        <el-button icon="el-icon-back" type="link" @click="goBack">返回</el-button>
        <h2>原子任务详情</h2>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="executeTask" :disabled="!canExecute">
          执行任务
        </el-button>
        <el-button type="success" @click="goToGitOperations">
          Git操作
        </el-button>
        <el-button type="primary" @click="goToDatabaseOperations">
          数据库操作
        </el-button>
        <el-button type="warning" @click="refreshTaskDetail">
          刷新
        </el-button>
      </div>
    </div>

    <!-- 任务基本信息 -->
    <el-card v-loading="loading" class="task-info-card">
      <template #header>
        <div class="card-header">
          <span>任务信息</span>
        </div>
      </template>
      <div v-if="task" class="task-info">
        <div class="info-section">
          <div class="info-item">
            <span class="label">任务ID：</span>
            <span>{{ task.id }}</span>
          </div>
          <div class="info-item">
            <span class="label">标题：</span>
            <span>{{ task.title }}</span>
          </div>
          <div class="info-item">
            <span class="label">描述：</span>
            <span>{{ task.description }}</span>
          </div>
          <div class="info-item">
            <span class="label">状态：</span>
            <el-tag :type="getStatusType(task.status)">
              {{ getStatusText(task.status) }}
            </el-tag>
          </div>
        </div>
        <div class="info-section">
          <div class="info-item">
            <span class="label">所属项目：</span>
            <span>{{ task.project_name }}</span>
          </div>
          <div class="info-item">
            <span class="label">主任务：</span>
            <span>{{ task.main_task_title }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span>{{ formatDate(task.created_at) }}</span>
          </div>
          <div class="info-item">
            <span class="label">最后更新：</span>
            <span>{{ formatDate(task.updated_at) }}</span>
          </div>
        </div>
        <div class="info-section">
          <div class="info-item">
            <span class="label">是否执行：</span>
            <el-tag :type="task.is_executed ? 'success' : 'info'">
              {{ task.is_executed ? '已执行' : '未执行' }}
            </el-tag>
          </div>
          <div class="info-item">
            <span class="label">执行次数：</span>
            <span>{{ task.execution_count || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="label">最后执行时间：</span>
            <span>{{ task.last_executed_at ? formatDate(task.last_executed_at) : '尚未执行' }}</span>
          </div>
          <div class="info-item">
            <span class="label">执行模式：</span>
            <el-tag type="info">{{ task.execution_mode === 'ai' ? 'AI执行' : '人工执行' }}</el-tag>
          </div>
        </div>
      </div>
      <el-empty v-else description="暂无任务信息" />
    </el-card>

    <!-- 操作历史标签页 -->
    <el-card class="operations-card">
      <template #header>
        <div class="card-header">
          <span>操作记录</span>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <!-- Git 操作 -->
        <el-tab-pane label="Git操作" name="git">
          <el-table :data="gitOperations" stripe style="width: 100%">
            <el-table-column prop="operation_type" label="操作类型" min-width="120">
              <template #default="scope">
                <el-tag :type="getOperationTypeTag(scope.row.operation_type)">
                  {{ getOperationTypeText(scope.row.operation_type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="git_repository_url" label="Git仓库" min-width="200" show-overflow-tooltip />
            <el-table-column prop="branch" label="分支" min-width="100" />
            <el-table-column prop="commit_hash" label="提交哈希" min-width="100" show-overflow-tooltip />
            <el-table-column prop="operation_time" label="操作时间" min-width="180">
              <template #default="scope">
                {{ formatDate(scope.row.operation_time) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" min-width="100">
              <template #default="scope">
                <el-tag :type="getStatusTag(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="!gitOperations.length" description="暂无Git操作记录" />
        </el-tab-pane>
        
        <!-- 数据库操作 -->
        <el-tab-pane label="数据库操作" name="db">
          <el-table :data="dbOperations" stripe style="width: 100%">
            <el-table-column prop="operation_type" label="操作类型" min-width="120">
              <template #default="scope">
                <el-tag :type="getOperationTypeTag(scope.row.operation_type)">
                  {{ getOperationTypeText(scope.row.operation_type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="db_name" label="数据库" min-width="150" />
            <el-table-column prop="table_name" label="表名" min-width="150" />
            <el-table-column prop="affected_rows" label="影响行数" min-width="100" />
            <el-table-column prop="operation_time" label="操作时间" min-width="180">
              <template #default="scope">
                {{ formatDate(scope.row.operation_time) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" min-width="100">
              <template #default="scope">
                <el-tag :type="getStatusTag(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="!dbOperations.length" description="暂无数据库操作记录" />
        </el-tab-pane>
        
        <!-- 文件操作 -->
        <el-tab-pane label="文件操作" name="file">
          <el-table :data="fileOperations" stripe style="width: 100%">
            <el-table-column prop="operation_type" label="操作类型" min-width="120">
              <template #default="scope">
                <el-tag :type="getOperationTypeTag(scope.row.operation_type)">
                  {{ getOperationTypeText(scope.row.operation_type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="file_path" label="文件路径" min-width="250" show-overflow-tooltip />
            <el-table-column prop="file_type" label="文件类型" min-width="100" />
            <el-table-column prop="operation_time" label="操作时间" min-width="180">
              <template #default="scope">
                {{ formatDate(scope.row.operation_time) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" min-width="100">
              <template #default="scope">
                <el-tag :type="getStatusTag(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="viewFileContent(scope.row)"
                >
                  查看内容
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="!fileOperations.length" description="暂无文件操作记录" />
        </el-tab-pane>
        
        <!-- 执行历史 -->
        <el-tab-pane label="执行历史" name="executions">
          <el-table :data="taskExecutions" stripe style="width: 100%">
            <el-table-column prop="id" label="执行ID" min-width="80" />
            <el-table-column prop="executor" label="执行者" min-width="100">
              <template #default="scope">
                <el-tag>{{ scope.row.executor === 'ai' ? 'AI' : '人工' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="execution_start" label="开始时间" min-width="180">
              <template #default="scope">
                {{ formatDate(scope.row.execution_start) }}
              </template>
            </el-table-column>
            <el-table-column prop="execution_end" label="结束时间" min-width="180">
              <template #default="scope">
                {{ scope.row.execution_end ? formatDate(scope.row.execution_end) : '进行中' }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" min-width="100">
              <template #default="scope">
                <el-tag :type="getExecutionStatusTag(scope.row.status)">
                  {{ getExecutionStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="200">
              <template #default="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="viewExecutionDetails(scope.row)"
                >
                  查看详情
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  :disabled="!scope.row.can_rollback || scope.row.status !== 'completed'"
                  @click="confirmRollback(scope.row)"
                >
                  回滚
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="!taskExecutions.length" description="暂无执行历史记录" />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 执行任务对话框 -->
    <el-dialog
      v-model="executeDialogVisible"
      title="执行任务"
      width="500px"
    >
      <p>任务: {{ task?.title }}</p>
      <p>描述: {{ task?.description }}</p>
      
      <el-form :model="executeForm" label-width="100px">
        <el-form-item label="执行方式">
          <el-radio-group v-model="executeForm.executor">
            <el-radio label="ai">AI执行</el-radio>
            <el-radio label="manual">人工执行</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="executeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExecuteTask" :loading="submitting">
          确认执行
        </el-button>
      </template>
    </el-dialog>

    <!-- 文件内容对话框 -->
    <el-dialog
      v-model="fileContentDialogVisible"
      title="文件内容"
      width="80%"
    >
      <div v-if="selectedFileOperation">
        <h4>文件路径: {{ selectedFileOperation.file_path }}</h4>
        
        <el-tabs v-model="fileContentTab">
          <el-tab-pane label="修改前" name="before">
            <pre class="code-block">{{ selectedFileOperation.content_before || '无内容' }}</pre>
          </el-tab-pane>
          <el-tab-pane label="修改后" name="after">
            <pre class="code-block">{{ selectedFileOperation.content_after || '无内容' }}</pre>
          </el-tab-pane>
          <el-tab-pane label="差异对比" name="diff">
            <div class="diff-container">
              <!-- 这里可以集成差异对比库 -->
              <p>差异对比功能待实现</p>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 执行详情对话框 -->
    <el-dialog
      v-model="executionDetailsDialogVisible"
      title="执行详情"
      width="80%"
    >
      <div v-if="selectedExecution">
        <div class="execution-info">
          <div class="info-item">
            <span class="label">执行ID:</span>
            <span>{{ selectedExecution.id }}</span>
          </div>
          <div class="info-item">
            <span class="label">状态:</span>
            <el-tag :type="getExecutionStatusTag(selectedExecution.status)">
              {{ getExecutionStatusText(selectedExecution.status) }}
            </el-tag>
          </div>
          <div class="info-item">
            <span class="label">执行者:</span>
            <span>{{ selectedExecution.executor === 'ai' ? 'AI' : '人工' }}</span>
          </div>
          <div class="info-item">
            <span class="label">开始时间:</span>
            <span>{{ formatDate(selectedExecution.execution_start) }}</span>
          </div>
          <div class="info-item">
            <span class="label">结束时间:</span>
            <span>{{ selectedExecution.execution_end ? formatDate(selectedExecution.execution_end) : '进行中' }}</span>
          </div>
        </div>
        
        <el-tabs v-model="executionDetailsTab">
          <el-tab-pane label="执行结果" name="result">
            <pre class="code-block">{{ selectedExecution.result || '无结果' }}</pre>
          </el-tab-pane>
          <el-tab-pane label="执行日志" name="log">
            <pre class="code-block">{{ selectedExecution.execution_log || '无日志' }}</pre>
          </el-tab-pane>
          <el-tab-pane v-if="selectedExecution.executor === 'ai'" label="AI提示" name="prompt">
            <pre class="code-block">{{ selectedExecution.ai_prompt || '无提示' }}</pre>
          </el-tab-pane>
          <el-tab-pane v-if="selectedExecution.executor === 'ai'" label="AI响应" name="response">
            <pre class="code-block">{{ selectedExecution.ai_response || '无响应' }}</pre>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 回滚确认对话框 -->
    <el-dialog
      v-model="rollbackDialogVisible"
      title="确认回滚"
      width="500px"
    >
      <p>您确定要回滚该执行吗？此操作将尝试还原该任务执行造成的所有更改。</p>
      
      <el-form :model="rollbackForm" label-width="100px">
        <el-form-item label="回滚原因">
          <el-input
            v-model="rollbackForm.reason"
            type="textarea"
            rows="3"
            placeholder="请输入回滚原因"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="rollbackDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="submitRollback" :loading="submitting">
          确认回滚
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'AtomicTaskDetail',
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  setup(props) {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()
    
    // 数据
    const task = ref(null)
    const loading = ref(false)
    const gitOperations = ref([])
    const dbOperations = ref([])
    const fileOperations = ref([])
    const taskExecutions = ref([])
    
    // UI控制
    const activeTab = ref('git')
    const executeDialogVisible = ref(false)
    const fileContentDialogVisible = ref(false)
    const executionDetailsDialogVisible = ref(false)
    const rollbackDialogVisible = ref(false)
    const fileContentTab = ref('before')
    const executionDetailsTab = ref('result')
    const selectedFileOperation = ref(null)
    const selectedExecution = ref(null)
    const submitting = ref(false)
    
    // 表单
    const executeForm = ref({
      executor: 'ai'
    })
    const rollbackForm = ref({
      reason: ''
    })
    
    // 计算属性
    const canExecute = computed(() => {
      return task.value && task.value.status === 'pending'
    })
    
    // 获取原子任务详情
    const fetchTaskDetail = async () => {
      loading.value = true
      try {
        const response = await store.dispatch('fetchAtomicTaskDetail', props.id)
        task.value = response.task
        gitOperations.value = response.git_operations || []
        dbOperations.value = response.db_operations || []
        fileOperations.value = response.file_operations || []
        taskExecutions.value = response.executions || []
      } catch (error) {
        ElMessage.error(`获取任务详情失败: ${error.message}`)
        
        // 模拟数据用于开发
        task.value = {
          id: props.id,
          title: '示例原子任务',
          description: '这是一个示例原子任务的描述',
          status: 'pending',
          project_name: '示例项目',
          main_task_title: '示例主任务',
          created_at: new Date(),
          updated_at: new Date(),
          is_executed: false,
          execution_count: 0,
          execution_mode: 'ai'
        }
      } finally {
        loading.value = false
      }
    }
    
    // 刷新任务详情
    const refreshTaskDetail = () => {
      fetchTaskDetail()
    }
    
    // 返回上一页
    const goBack = () => {
      router.back()
    }
    
    // 执行任务
    const executeTask = () => {
      executeForm.value.executor = 'ai'
      executeDialogVisible.value = true
    }
    
    // 跳转到Git操作页面
    const goToGitOperations = () => {
      router.push({
        name: 'GitTaskDetail',
        params: { id: props.id },
        query: { type: 'sub' }
      })
    }
    
    // 跳转到数据库操作页面
    const goToDatabaseOperations = () => {
      router.push({
        name: 'DatabaseTaskDetail',
        params: { id: props.id }
      })
    }
    
    // 提交执行任务
    const submitExecuteTask = async () => {
      submitting.value = true
      try {
        await store.dispatch('executeTask', {
          subtaskId: props.id,
          executor: executeForm.value.executor
        })
        
        executeDialogVisible.value = false
        ElMessage.success('任务执行请求已提交')
        
        // 如果是人工执行，导航到执行页面
        if (executeForm.value.executor === 'manual') {
          router.push(`/tasks/${props.id}/execution`)
        } else {
          // 刷新任务详情
          setTimeout(() => {
            refreshTaskDetail()
          }, 1000)
        }
      } catch (error) {
        ElMessage.error(`任务执行失败: ${error.message}`)
      } finally {
        submitting.value = false
      }
    }
    
    // 查看文件内容
    const viewFileContent = (fileOperation) => {
      selectedFileOperation.value = fileOperation
      fileContentTab.value = 'before'
      fileContentDialogVisible.value = true
    }
    
    // 查看执行详情
    const viewExecutionDetails = (execution) => {
      selectedExecution.value = execution
      executionDetailsTab.value = 'result'
      executionDetailsDialogVisible.value = true
    }
    
    // 确认回滚
    const confirmRollback = (execution) => {
      selectedExecution.value = execution
      rollbackForm.value.reason = ''
      rollbackDialogVisible.value = true
    }
    
    // 提交回滚
    const submitRollback = async () => {
      if (!selectedExecution.value) return
      
      if (!rollbackForm.value.reason.trim()) {
        ElMessage.warning('请输入回滚原因')
        return
      }
      
      submitting.value = true
      try {
        await store.dispatch('rollbackExecution', {
          executionId: selectedExecution.value.id,
          reason: rollbackForm.value.reason
        })
        
        rollbackDialogVisible.value = false
        ElMessage.success('回滚请求已提交')
        
        // 刷新任务详情
        setTimeout(() => {
          refreshTaskDetail()
        }, 1000)
      } catch (error) {
        ElMessage.error(`回滚失败: ${error.message}`)
      } finally {
        submitting.value = false
      }
    }
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '-'
      const date = new Date(dateStr)
      return date.toLocaleString()
    }
    
    // 获取状态标签类型
    const getStatusType = (status) => {
      const statusMap = {
        'pending': 'info',
        'in_progress': 'warning',
        'completed': 'success',
        'failed': 'danger',
        'blocked': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待执行',
        'in_progress': '执行中',
        'completed': '已完成',
        'failed': '失败',
        'blocked': '阻塞'
      }
      return statusMap[status] || status
    }
    
    // 获取操作类型标签
    const getOperationTypeTag = (type) => {
      const typeMap = {
        // Git操作
        'clone': 'success',
        'pull': 'info',
        'push': 'warning',
        'commit': 'primary',
        'branch': 'success',
        'checkout': 'info',
        
        // 数据库操作
        'query': 'info',
        'insert': 'success',
        'update': 'warning',
        'delete': 'danger',
        'alter': 'primary',
        
        // 文件操作
        'create': 'success',
        'read': 'info',
        'update': 'warning',
        'delete': 'danger',
        'move': 'primary',
        'copy': 'success'
      }
      return typeMap[type] || 'info'
    }
    
    // 获取操作类型文本
    const getOperationTypeText = (type) => {
      return type
    }
    
    // 获取状态标签
    const getStatusTag = (status) => {
      const statusMap = {
        'pending': 'info',
        'success': 'success',
        'failed': 'danger',
        'running': 'warning'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取执行状态标签
    const getExecutionStatusTag = (status) => {
      const statusMap = {
        'running': 'warning',
        'completed': 'success',
        'failed': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取执行状态文本
    const getExecutionStatusText = (status) => {
      const statusMap = {
        'running': '执行中',
        'completed': '已完成',
        'failed': '失败'
      }
      return statusMap[status] || status
    }
    
    // 初始化
    onMounted(() => {
      fetchTaskDetail()
    })
    
    return {
      task,
      loading,
      gitOperations,
      dbOperations,
      fileOperations,
      taskExecutions,
      activeTab,
      executeDialogVisible,
      fileContentDialogVisible,
      executionDetailsDialogVisible,
      rollbackDialogVisible,
      fileContentTab,
      executionDetailsTab,
      selectedFileOperation,
      selectedExecution,
      executeForm,
      rollbackForm,
      submitting,
      canExecute,
      goBack,
      refreshTaskDetail,
      executeTask,
      submitExecuteTask,
      viewFileContent,
      viewExecutionDetails,
      confirmRollback,
      submitRollback,
      formatDate,
      getStatusType,
      getStatusText,
      getOperationTypeTag,
      getOperationTypeText,
      getStatusTag,
      getExecutionStatusTag,
      getExecutionStatusText,
      goToGitOperations,
      goToDatabaseOperations
    }
  }
}
</script>

<style scoped>
.atomic-task-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
}

.page-title h2 {
  margin: 0 0 0 10px;
}

.task-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.info-section {
  flex: 1;
  min-width: 300px;
}

.info-item {
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
}

.info-item .label {
  font-weight: bold;
  width: 100px;
  display: inline-block;
}

.operations-card {
  margin-bottom: 20px;
}

.code-block {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  max-height: 400px;
  overflow: auto;
  font-family: monospace;
  white-space: pre-wrap;
}

.diff-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  max-height: 400px;
  overflow: auto;
}

.execution-info {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.execution-info .info-item {
  margin-bottom: 0;
  min-width: 200px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 